class Listen2Scene extends Scene {

    private returnBtn: eui.Image;
    private listenMenuBtn: eui.Image;
    private introduceBtn: eui.Image;
    private previousBtn: eui.Image;//上一句
    private nextBtn: eui.Image;//下一句
    private playAgainBtn: eui.ToggleButton;//重读一遍
    private listenMoreLabel: eui.Image;
    private startDictationLabel: eui.Image;
    private blanksGroup: eui.Group;//单词挖空的容器
    private answerGroup: eui.Group;//完整句子和翻译的容器
    private transparentMask: eui.Rect;//透明遮罩
    private choicesGroup: eui.Group;//单词选项的容器

    private listeningID: number;
    private material: ListeningMaterial;
    private audioContext: wx.InnerAudioContext;
    private currentSentenceIndex: number;
    //当前句子的所有单词
    private currentWords: string[];
    //当前句子未挖空单词的索引
    private currentNotBlankWords: number[];
    //当前句子挖空的正确答案
    private currentAnswers: string[] = [];
    //当前的所有选项
    private currentChoices: string[];
    //当前正在做的挖空的序号
    private currentBlankIndex: number;
    //答题的错误次数，超过三次会强制重新播放一遍这句话
    private errorCount: number;
    //当前句子的开始和结束时间
    private sentenceStartTime = -1;
    private sentenceEndTime = -1;

    public constructor(listeningID?: number, listeningMaterial?: ListeningMaterial) {
        super();
        this.listeningID = listeningID;
        this.material = listeningMaterial;
    }

    public onSkinLoaded() {
        this.initListener();
        if (this.material != null) this.initAudioAndBlanks();
        else this.initData();
    }

    //初始化监听器
    private initListener() {
        this.returnBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.listenMenuBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.introduceBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.previousBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.nextBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.playAgainBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.transparentMask.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            this.startDictationLabel.visible = false;
            this.transparentMask.includeInLayout = false;
            this.transparentMask.visible = false;
            this.currentChoices = this.currentAnswers.slice(0);
            this.updateChoices();
        }, this)
    }

    //初始化数据
    private initData() {
        wx.request({
            url: Constants.HTTP_SERVER_URL + "listening/" + this.listeningID,
            method: "GET",
            success: (res) => {
                if (res.statusCode == 200) {
                    this.material = new ListeningMaterial(<{}>res.data);
                    this.currentSentenceIndex = 0;
                    this.initAudioAndBlanks();

                }
            },
            fail: (err) => {
                console.log(err);
            }
        });
    }

    //初始化InnerAudioContext和挖空
    private initAudioAndBlanks() {
        this.audioContext = wx.createInnerAudioContext();
        this.audioContext.src = Constants.HTTP_SERVER_URL + "resource/" + this.material.filePath;
        this.audioContext.onTimeUpdate(() => {
            console.log("onTimeUpdate")
            // let currentTime = this.audioContext.currentTime;
            // if (currentTime >= this.sentenceEndTime) {
            //     this.audioContext.pause();
            //     this.startExercise();
            // }
            // console.log(this.sentenceEndTime);
        });
        //this.audioContext.play();
        this.currentSentenceIndex = 0;
        this.updateSentence();
        this.startExercise();
    }

    private startExercise() {
        this.listenMoreLabel.visible = false;
        this.startDictationLabel.visible = true;
        this.transparentMask.visible = true;
        
    }

    //更新语句
    private updateSentence() {
        this.currentWords = this.material.content[this.currentSentenceIndex].split(" ");
        this.processPuncs(this.currentWords);
        this.currentNotBlankWords = this.material.notBlankedWords[this.currentSentenceIndex];
        this.updateSentenceTime();
        this.updateBlanks();
    }

    //更新当前语句的开始和结束时间
    private updateSentenceTime() {
        if (this.currentSentenceIndex == 0) {
            this.sentenceStartTime = 0;
        } else {
            this.sentenceStartTime = this.material.sentenceBreakTimes[this.currentSentenceIndex - 1];
        }

        if (this.currentSentenceIndex == this.material.sentenceCount - 1) {
            this.sentenceEndTime = this.material.soundTime;
        } else {
            this.sentenceEndTime = this.material.sentenceBreakTimes[this.currentSentenceIndex];
        }
    }

    //更新挖空的内容
    private updateBlanks() {
        this.currentBlankIndex = 0;
        this.errorCount = 0;
        this.blanksGroup.removeChildren();
        for (let i = 0; i < this.currentWords.length; i++) {
            let blankView = new BlankView();
            blankView.word = this.currentWords[i];
            if (this.currentNotBlankWords.indexOf(i) != -1) {
                blankView.type = WORD_ONLY;
            } else {
                blankView.type = LINE_ONLY;
                this.currentAnswers.push(blankView.word.toLowerCase());
            }
            this.blanksGroup.addChild(blankView);
        }
    }

    //初始化或更新当前语句的选项
    public updateChoices() {
        //将选项顺序打乱
        for (let i = 0; i < this.currentChoices.length; i++) {
            let j = Math.floor(Math.random() * this.currentChoices.length);
            let temp = this.currentChoices[i];
            this.currentChoices[i] = this.currentChoices[j];
            this.currentChoices[j] = temp;
        }
        //生成选项按钮
        this.choicesGroup.removeChildren();
        for (let choice of this.currentChoices) {
            let choiceButton = new eui.Button();
            choiceButton.skinName = "resource/skins/view/BlankChoice.exml";
            choiceButton.label = choice;
            choiceButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.choiceClick, this);
            this.choicesGroup.addChild(choiceButton);
        }
    }

    //将单词末尾可能的标点符号去掉
    public processPuncs(words: string[]) {
        for (let i = 0; i < words.length; i++) {
            let word = words[i];
            let lastLetter = word[word.length - 1].toLowerCase()
            if (lastLetter > 'z' || lastLetter < 'a') {
                words[i] = word.substring(0, word.length - 1);
            }
        }
    }

    public initAnswerGroup() {
        let sentenceLabel = this.answerGroup.getChildAt(0) as eui.Label;
        let translateLabel = this.answerGroup.getChildAt(1) as eui.Label;
        sentenceLabel.text = this.material.content[this.currentSentenceIndex];
        translateLabel.text = this.material.translation[this.currentSentenceIndex];
    }

    public previousSentence() {

    }

    public nextSentence() {
        this.currentSentenceIndex++;
        this.updateSentence();
        this.audioContext.play();
    }

    private btnHandler(evt: egret.TouchEvent) {
        let btnFocused = evt.currentTarget;
        switch (btnFocused) {
            case this.returnBtn:
                this.audioContext.destroy();
                SceneManager.instance.removeScene(this);
                break;

            case this.listenMenuBtn:

                break;
            case this.introduceBtn:
                break;
            case this.previousBtn:
                this.previousSentence();
                break;
            case this.nextBtn:
                this.answerGroup.visible = false;
                this.blanksGroup.visible = true;
                this.nextSentence();
                break;
            case this.playAgainBtn:
                break;

        }
    }

    private errorBtnIndex = -1;
    //选项的点击事件
    private choiceClick(evt: egret.TouchEvent) {
        if (this.errorBtnIndex != -1) {
            (<eui.Button>this.choicesGroup.getChildAt(this.errorBtnIndex)).currentState = "normal";
        }
        let choiceButton = <eui.Button>evt.currentTarget;
        let choice = choiceButton.label;
        if (choice == this.currentAnswers[this.currentBlankIndex].toLowerCase()) {
            let index = this.choicesGroup.getChildIndex(choiceButton);
            this.currentChoices.splice(index, 1);
            this.currentBlankIndex++;
            this.updateChoices();
            let blankIndex = 0;
            for (let i = 0; i < this.currentWords.length; i++) {
                let blankView = this.blanksGroup.getChildAt(i) as BlankView;
                if (blankView.type == WORD_ONLY) continue;
                if (blankIndex == this.currentBlankIndex - 1) {
                    blankView.type = WORD_AND_LINE;
                    break;
                }
                blankIndex++;
            }
            this.errorBtnIndex = -1;
            if (this.choicesGroup.numChildren == 0) {
                this.initAnswerGroup();
                this.blanksGroup.visible = false;
                this.answerGroup.visible = true;
            }
        } else {
            choiceButton.currentState = "error";
            this.errorBtnIndex = this.choicesGroup.getChildIndex(choiceButton);
            this.errorCount++;
        }
    }
}